package com.succez.server.servlet.http;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.succez.server.pojo.FileInfo;
import com.succez.server.servlet.Consts;
import com.succez.server.servlet.Request;
import com.succez.server.servlet.Response;
import com.succez.server.servlet.Servlet;
import com.succez.server.utils.CloseUtil;

public class FileSystemServlet extends Servlet {

    /**
     * 当前路径
     */
    private static final File currentDirectoty = new File(".");

    /**
     * 赋予id时的累加器
     */
    private static int count = 0;

    /**
     * 递归获取目录下所有文件
     */
    private void recurFiles(List<FileInfo> rawResponse, List<FileInfo> parentFiles, int marginGrade)
            throws IOException {
        if (parentFiles.size() == 0)
            return;
        List<FileInfo> recurFileInfos = new ArrayList<>();
        for (FileInfo fileInfo : parentFiles) {
            File currFile = new File(currentDirectoty.getCanonicalPath(), fileInfo.getPath());
            File[] files = currFile.listFiles();
            if (files != null) {
                for (File newFile : files) {
                    count++;
                    FileInfo newFileInfo = new FileInfo();
                    newFileInfo.setId(System.currentTimeMillis() + "" + count);
                    newFileInfo.setParentId(fileInfo.getId());
                    newFileInfo.setFileName(newFile.getName());
                    newFileInfo.setDirectory(newFile.isDirectory());
                    newFileInfo.setPath(fileInfo.getPath() + "\\" + newFile.getName());
                    newFileInfo.setMarginGrade(marginGrade);
                    rawResponse.add(newFileInfo);
                    if (newFileInfo.isDirectory()) {
                        recurFileInfos.add(newFileInfo);
                    }
                }
            }
        }
        recurFiles(rawResponse, recurFileInfos, marginGrade + 1);
    }

    /**
     * 文件请求、修改、目录请求
     */
    @Override
    protected void doPost(Response response, Request request) {

        // 页面初始化
        String queryJson = request.getQueryParams().get("jsonObject");
        if (queryJson == null || queryJson.equals("")) {
            File docRoot;
            try {
                docRoot = new File(currentDirectoty.getCanonicalPath(), Consts.DOC_ROOT);
                File[] files = docRoot.listFiles();
                List<FileInfo> rawResponse = new ArrayList<>();
                List<FileInfo> initParentFiles = new ArrayList<>();
                for (File file : files) {
                    count++;
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setId(System.currentTimeMillis() + "" + count);
                    fileInfo.setParentId("");
                    fileInfo.setMarginGrade(0);
                    fileInfo.setFileName(file.getName());
                    fileInfo.setDirectory(file.isDirectory());
                    fileInfo.setPath(Consts.DOC_ROOT + "\\" + file.getName());
                    rawResponse.add(fileInfo);
                    if (file.isDirectory()) {
                        initParentFiles.add(fileInfo);
                    }
                }
                // 对每一个进行递归查找
                if (initParentFiles.size() != 0) {
                    recurFiles(rawResponse, initParentFiles, 1);
                }

                String bodyText = JSON.toJSONString(rawResponse);
                response.setBodyText(bodyText);
                response.setStatusLine(200);
                response.setHeadInfo("Content-Type", "application/json");
                response.pushToClient();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (queryJson != null && !queryJson.equals("")) {
            // 如果是目录，则返回目录下的文件（目录），如果是目录则在content中显示内容
            FileInfo fileInfo = JSON.parseObject(queryJson, FileInfo.class);
            try {
                if (fileInfo.isDirectory()) {
                    // 目录的处理
                    handleDirectory(fileInfo, response, request);
                } else {
                    // 文件的处理
                    handleFile(fileInfo, response, request);
                }
            } catch (IOException e) {
                
                e.printStackTrace();
            }
        }
    }

    private void handleFile(FileInfo fileInfo, Response resp, Request req) throws IOException {
        File file = new File(currentDirectoty.getCanonicalPath(), fileInfo.getPath());
        if (fileInfo.isSave()) {
            // 保存文件
            BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(file));
            byte[] data = fileInfo.getFileText().getBytes();
            bo.write(data);
            bo.flush();
            CloseUtil.colseIo(bo);
            fileInfo.setSave(false);
            fileInfo.setSaveStatus(true);
            String bodyText = JSON.toJSONString(fileInfo);
            resp.setBodyText(bodyText);
            resp.setStatusLine(200);
            resp.setHeadInfo("Content-Type", "application/json");
            resp.pushToClient();
        } else {
            // 读取文件
            BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));
            byte[] data = new byte[bi.available()];
            int len = bi.read(data);
            CloseUtil.colseIo(bi);
            String fileText = new String(data, 0, len);
            fileInfo.setFileText(fileText);
            String bodyText = JSON.toJSONString(fileInfo);
            resp.setBodyText(bodyText);
            resp.setStatusLine(200);
            resp.setHeadInfo("Content-Type", "application/json");
            resp.pushToClient();
        }
    }

    private void handleDirectory(FileInfo fileInfo, Response resp, Request req) throws IOException {
        // 返回目录信息
        File directory = new File(currentDirectoty.getCanonicalPath(), fileInfo.getPath());
        if (directory.exists()) {
            File[] files = directory.listFiles();
            List<FileInfo> rawResponse = new ArrayList<>();
            for (File file : files) {
                FileInfo pFile = new FileInfo();
                pFile.setFileName(file.getName());
                pFile.setDirectory(file.isDirectory());
                pFile.setPath(fileInfo.getPath() + "\\" + file.getName());
                rawResponse.add(pFile);
            }
            String bodyText = JSON.toJSONString(rawResponse);
            resp.setBodyText(bodyText);
            resp.setStatusLine(200);
            resp.setHeadInfo("Content-Type", "application/json");
            resp.pushToClient();
        }
    }

    /**
     * 文件下载
     */
    @Override
    protected void doGet(Response response, Request request) {
        String path = request.getQueryParams().get("path");
        try {
            File file = new File(currentDirectoty.getCanonicalPath(), path);
            String filename = file.getName();
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            int len = fis.read(buffer);
            fis.close();
            StringBuilder sb = new StringBuilder();
            sb.append("HTTP/1.1 200 OK").append(Consts.CRLF);
            sb.append("Content-Disposition:attachment;filename=" + filename).append(Consts.CRLF);
            sb.append("Content-Length:" + len).append(Consts.CRLF);
            sb.append("Content-Type:application/octet-stream").append(Consts.CRLF);
            sb.append(Consts.CRLF);
            sb.append(new String(buffer, 0, len));
            BufferedOutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(sb.toString().getBytes());
            toClient.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}